var ImagePlugins = function () {

    return {
        //main function to initiate the module
    	hasInit : false,
    	imgArr : [],
    	divId :	"",
    	mutiple : true,
    	type : 'type',
    	imgItem : '',
    	imgHost : '',
    	uploadCount : 0,
    	uploadSuccess : 0,
    	uploadError : 0,
    	uploadCompleted :0,
    	fileDbPath : {},
    	init : function(_param) {
			ImagePlugins.addSimpleItem(_param);
			ImagePlugins.setListener(_param);
    	},
    	fixImageContext : function(_param){
    		var delBtn = "<a title='删除' style='display:inline-block;' class='btn btn-sm btn-icon btn-danger' href='#' onclick='' type='delImagePlugins'><i class='fa fa-times'></i></a>";
    		var imgSrc = _param.imgpath? (imgCtx + _param.imgpath) : ctx + '/images/nopic.jpg';
    		if(!_param.mutiple){
    			delBtn = "";
    		}
    		var imgDbpath = _param.imgpath?'dbpath="' + _param.imgpath + '"':'';
    		var simpleItem = jQuery('<div>'+
				'<div class="work">'+
                    '<div class="image" style="border: 1px solid #e1e1e1;">'+
                        '<a href="javascript:void(0);"><img src="'+imgSrc+'" onerror="javascript:this.src=\''+ctx+'/images/nopic.jpg\'" alt="Photo" /></a>'+
                    '</div>'+
                    '<div class="desc">'+
                    	'<div class="px-widget ui-widget" id="px-widget-1">'+
                    		'<div class="ui-helper-clearfix">'+
                    			'<div class="px-form-input" id="px-form-1-input" style="display:inline-block;">'+
                    				'<div class="px-input-button ui-button" role="button">'+
										'<span>'+
											'<span><a title="上传" class="btn btn-sm btn-icon btn-success" href="#" onclick="" type="addImagePlugins"><i class="fa fa-upload"></i></a></span>'+
											'<input type="file" name="filename" class="file">'+
											'<button name="px-submit" type="submit" style="display:none;">Upload</button>'+
										'</span>'+
									'</div>'+
								'</div>'+
								delBtn+
							'</div>'+
						'</div>'+
					'</div>'+
                '</div>'+
			'</div>');
    		return simpleItem;
    	},
    	fixFileContext : function(_param){
    		var delBtn = "<a title='删除' style='display:inline-block;' class='btn btn-sm btn-icon btn-danger' href='#' onclick='' type='delImagePlugins'><i class='fa fa-times'></i></a>";
    		if(!_param.mutiple){
    			delBtn = "";
    		}
    		var imgSrc = _param.imgpath? (imgCtx + _param.imgpath) : ctx + '/images/nopic.jpg';
    		console.info(imgSrc);
    		var imgDbpath = _param.imgpath?'dbpath="' + _param.imgpath + '"':'';
    		var simpleItem = jQuery('<div>'+
				'<div class="work">'+
                    '<div class="image" style="border: 1px solid #e1e1e1;">'+
                        '<a href="javascript:void(0);"><img src="'+imgSrc+'" onerror="javascript:this.src=\''+ctx+'/images/nopic.jpg\'" alt="Photo" /></a>'+
                    '</div>'+
                    '<div class="desc">'+
                    	'<div class="px-widget ui-widget" id="px-widget-1">'+
                    		'<div class="ui-helper-clearfix">'+
                    			'<div class="px-form-input" id="px-form-1-input" style="display:inline-block;">'+
                    				'<div class="px-input-button ui-button" role="button">'+
										'<span>'+
											'<span><a title="上传" class="btn btn-sm btn-icon btn-success" href="#" onclick="" type="addImagePlugins"><i class="fa fa-upload"></i></a></span>'+
											'<input type="file" name="filename" class="file">'+
											'<button name="px-submit" type="submit" style="display:none;">Upload</button>'+
										'</span>'+
									'</div>'+
								'</div>'+
								delBtn+	
							'</div>'+
						'</div>'+
					'</div>'+
                '</div>'+
			'</div>');
    		return simpleItem;
    	},
    	addSimpleItem : function(_param) {
    		if (jQuery("#"+_param.place).attr("hasInit")=="1") {
    			return;
    		}
    		var simpleItem = "";
    		if (_param.type == "file") {
    			simpleItem = ImagePlugins.fixFileContext(_param);
    		} else {
    			simpleItem = ImagePlugins.fixImageContext(_param);
    		}
    		jQuery("#"+_param.place).eq(0).append(simpleItem);
    		var currentLi = jQuery("#"+_param.place).eq(0).parent();
    		if (_param.type == "image") {
    			currentLi.find(".file").attr("accept", "image/*");
    		}
    		if (_param.mutiple) {
    			currentLi.find(".file").attr("multiple", "multiple");
    		}
    		
    		var _index = jQuery("#"+_param.place).find(".file").length == 0 ? 1 : jQuery("#"+_param.place).find(".file").length + 1;

    		jQuery("#"+_param.place).attr("isMutiple", _param.mutiple);
    		jQuery("#"+_param.place).attr("setMain", _param.setMain);
    		jQuery("#"+_param.place).attr("hasInit", "1");

    		ImagePlugins.setChangeListener(_param);
    		ImagePlugins.hasInit = true;

    	},
    	setListener : function(_param) {
    		//绑定删除事件
    		jQuery("body").on("click", "#"+_param.place+" a[type='delImagePlugins']", function(index){
    			var _index = jQuery(this).parents("#"+_param.place).find("a[type='delImagePlugins']").index(jQuery(this));
    			var imgCount = jQuery("#"+_param.place).find(".work").length;
    			if (imgCount > 1) {
    				jQuery(this).parents("#"+_param.place).find(".work").eq(_index).parent().remove();
    			}
    		});
    	},
    	
    	setChangeListener2 : function(_param, _imgObj) {
            var uploadDefaultType = this.type;
            jQuery(_imgObj).change(function(){
                var uimg = jQuery(_imgObj);
                uimg.attr("currentFile", "1");
                var _index = uimg.parents("#"+_param.place).find("input[type=file]").index(uimg);
                //var uform = uimg.parents().find("form[_type='imgUpload']").eq(_index);
                var fileInput = this;
                var files = this.files;
                jQuery.each(files, function (index, file) {
                    var fd = new FormData();
                    fd.append("type", _param.type ? _param.type : uploadDefaultType);
                    //添加thums
                    if(_param.thums && _param.thums instanceof Array){
                        for(var thumIndex=0;thumIndex<_param.thums.length;thumIndex++){
                            var thum = _param.thums[thumIndex];
                            if(!thum.key){
                                continue;
                            }
                            if(thum.scale){
                                fd.append("thum."+thum.key+".scale", thum.scale);
                            }else if(thum.width&&thum.height){
                                fd.append("thum."+thum.key+".size", ""+thum.width+","+thum.height);
                            }
                        }
                    }
                    fd.append($(fileInput).attr('name'), file);
                    jqxhr = $.ajax({
                        //url: uform.attr('action'),
                        url : ctx+'/imageUpload/uploadFile',
                        data: fd,
                        cache: false,
                        contentType: false,
                        processData: false,
                        type: 'POST'
                    })
                    .success(function(data) {
                    })
                    .error(function(jqXHR, textStatus, errorThrown) {
                    })
                    .complete(function(jqXHR, textStatus) {
                        if (jqXHR.status=="200") {
                            var data = jqXHR.responseText;
                            if (data) {
                                var array = eval('(' + data + ')');
                                if (array.length>0) {
                                    if (_param.mutiple==false||_param.mutiple=="false") {
                                        //单张图片控件
                                        for (var i=0;i<array.length;i++) {
                                            uimg.parents("#"+_param.place).find("img[alt='Photo']").eq(_index).attr("src", array[i].serverPath).attr("dbpath", array[i].serverPath).attr("img_width", array[i].width).attr("img_height", array[i].height);
                                        }
                                    } else {
                                        if (uimg.attr("currentFile")=="1") {
                                            uimg.parents("#"+_param.place).find("img[alt='Photo']").eq(_index).attr("src", array[0].serverPath).attr("dbpath", array[0].serverPath).attr("img_width", array[0].width).attr("img_height", array[0].height);
                                            uimg.removeAttr("currentFile");
                                        } else {
                                            jQuery("#"+_param.place).attr("hasInit", "0");
                                            ImagePlugins.addSimpleItem({"place":_param.place, "mutiple":_param.mutiple, "imgpath":array[0].serverPath, "imgWidth":array[0].width, "imgHeight":array[0].height});
                                        }
                                    }
                                }
                            }
                        }
                    });
                });
            });
        },
    	
    	
    	setChangeListener : function(_param) {
    		jQuery("body").on("change", "div[id='"+_param.place+"'] .file",function() {
    			var uploadDefaultType = "image";
    			ImagePlugins.fileDbPath = [];
    			jQuery(".fixDD").show();
    			var uimg = jQuery(this);
    			uimg.attr("currentFile", "1");
    			var _index = jQuery("div[id='"+_param.place+"'] .file").index(uimg);
    			//var uform = uimg.parents().find("form[_type='imgUpload']").eq(_index);
    			var fileInput = this;
    			var files = this.files;
    			ImagePlugins.uploadCount = files.length;
    			ImagePlugins.uploadSuccess = 0;
    			ImagePlugins.uploadError = 0;
    			jQuery("#uploadCount").html(files.length);
    			var ufilePath = ctx+'/imageUpload/uploadFile';
    			if(_param.remote){
    				ufilePath += ("?remote=false");//远程上传
    			}
    			jQuery.each(files, function (index, file) {
    				
    				var fd = new FormData();
    				fd.append($(fileInput).attr('name'), file);
    				console.info("_param.type:" + _param.type);
    				
    				if(_param.type){
    					uploadDefaultType = _param.type;
    				} else {
    					_param.type = uploadDefaultType;
    				}
    				fd.append("type", uploadDefaultType);

    				//添加thums
                    if(_param.thums && _param.thums instanceof Array){
                        for(var thumIndex=0;thumIndex<_param.thums.length;thumIndex++){
                            var thum = _param.thums[thumIndex];
                            if(!thum.key){
                                continue;
                            }
                            if(thum.scale){
                                fd.append("thum."+thum.key+".scale", thum.scale);
                            }else if(thum.width&&thum.height){
                                fd.append("thum."+thum.key+".size", ""+thum.width+","+thum.height);
                            }
                        }
                    }
    				
    				jqxhr = $.ajax({
    					url : ufilePath,
    					data: fd,
    					cache: false,
    					async: false,
    					contentType: false,
    					processData: false,
    					type: 'POST'
    				}).success(function(data) {
    					
    				}).error(function(jqXHR, textStatus, errorThrown) {
    					
    				}).complete(function(jqXHR, textStatus) {
    					if (jqXHR.status=="200") {
    						ImagePlugins.uploadSuccess = ImagePlugins.uploadSuccess + 1;
    						jQuery("#uploadSuccess").html(ImagePlugins.uploadSuccess);
    						var data = jqXHR.responseText;
    						if (data) {
								var array = eval('(' + data + ')');
    							if (array.length > 0) {
    								if (_param.type == "image") {
    									if (uimg.attr("currentFile")=="1") {
    										jQuery("div[id='"+_param.place+"'] img[alt='Photo']").eq(_index).attr("src", array[0].serverPath);
    										uimg.removeAttr("currentFile");
    										jQuery("div[id='"+_param.place+"'] img[alt='Photo']").eq(_index).attr("dbPath", array[0].serverPath).attr("title", array[0].originalName);
    									} else {
    										_param.imgPath = array[0].imgPath;
    										_param.dbPath = array[0].serverPath;
    										_param.title = array[0].originalName;
            								ImagePlugins.addCallBack(_param);
    									}
    								}else if(_param.type == 'file'){
    									if (uimg.attr("currentFile")=="1") {
    										jQuery("div[id='"+_param.place+"'] img[alt='Photo']").eq(_index).attr("src", ctx+"/image/file.jpg").attr("filepath", array[0].serverPath);
    										uimg.removeAttr("currentFile");
    										jQuery("div[id='"+_param.place+"'] img[alt='Photo']").eq(_index).attr("dbPath", array[0].serverPath).attr("title", array[0].originalName);
    									} else {
    										_param.imgPath = array[0].imgPath;
    										_param.dbPath = array[0].serverPath;
    										_param.title = array[0].originalName;
            								ImagePlugins.addCallBack(_param);
    									}
    								}
    								ImagePlugins.fileDbPath.push(array[0].serverPath);
    							}
    							
    						}
    						ImagePlugins.closeDialog();
    					} else {
    						//上传失败
    						ImagePlugins.uploadError = ImagePlugins.uploadError + 1;
    						jQuery("#uploadError").html(ImagePlugins.uploadError);
    						ImagePlugins.closeDialog();
    					}
    				});
    			});
    		});
    	},
    	/**
    	 * 上传提示
    	 */
    	closeDialog : function() {
    		ImagePlugins.uploadCompleted = ImagePlugins.uploadError + ImagePlugins.uploadSuccess;
    		if (ImagePlugins.uploadCount == ImagePlugins.uploadCompleted) {
    			setTimeout(function(){jQuery(".fixDD").hide();}, 1000);
    		}
    	},
    	addImgBySrc : function(_divId,_dbPath) {
    		var imgTemplate = jQuery("#"+_divId).children().eq(0);
    		if (jQuery("#"+_divId).attr("isMutiple")=="false" || jQuery("#"+_divId).attr("isMutiple")==false) {
    			jQuery(imgTemplate).removeAttr("isTemplate");
    			jQuery(imgTemplate).find("img[alt='Photo']").eq(0).attr("src", imgCtx + _dbPath);
    			jQuery(imgTemplate).find("img[alt='Photo']").eq(0).attr("dbPath", _dbPath);
    			//ImagePlugins.setChangeListener({"place":_divId, "mutiple":jQuery("#"+_divId).attr("isMutiple")}, imgTemplate.find(".file"));
    		} else {
    			jQuery("#" +_divId + " li[isTemplate='true']").remove();
    			jQuery("#" +_divId).attr("hasInit", "0");
    			ImagePlugins.addSimpleItem({"place":_divId, "mutiple":jQuery("#"+_divId).attr("isMutiple"), "imgpath":_dbPath});
    			jQuery("#" +_divId + " li[isTemplate='true']").removeAttr("isTemplate");
    			var tempImg = jQuery(imgTemplate).clone(true);
    			/*jQuery(tempImg).removeAttr("isTemplate");
    			jQuery(tempImg).find("img[alt='Photo']").eq(0).attr("src", ImagePlugins.imgHost + _dbPath);
    			jQuery(tempImg).find("img[alt='Photo']").eq(0).attr("dbPath", _dbPath);
    			jQuery(tempImg).appendTo(jQuery("#"+_divId));
    			ImagePlugins.setChangeListener({"place":_divId, "mutiple":jQuery("#"+_divId).attr("isMutiple")}, tempImg.find(".file"));
    			jQuery("#" +_divId + " div[isTemplate='true']").remove();*/
    		}
        },
        addCallBack : function(_param) {
    		var filePaths = _param.imgPath.split(",");
			for (var i = 0 ;i < filePaths.length; i++) {
				var newLi = jQuery("div[id='"+_param.place+"']").eq(0).clone(true);
				if (_param.type == "image") {
					newLi.find("img[alt='Photo']").eq(0).attr("src", imgCtx + filePaths[i]).attr("dbpath", _param.dbPath).attr("title", _param.title);
				}else if(_param.type=="file"){
					newLi.find("img[alt='Photo']").eq(0).attr("src", ctx+"/image/file.jpg").attr("filepath", imgCtx + filePaths[i]).attr("dbpath", _param.dbPath).attr("title", _param.title);
				}
				jQuery("div[id='"+_param.place+"']").last().after(newLi);
    			//是否允许设置主图
        		//jQuery(this).attr("setMain", _param.setMain);
			}
    	},
        clearPlugin : function(_divId) {
        	if (jQuery("#"+_divId).children().length==0) {
        		return;
        	}
        	var isMutiple = jQuery("#"+_divId).attr("isMutiple");
        	var setMain = jQuery("#"+_divId).attr("setMain");
        	jQuery("#"+_divId).attr("hasInit", "0");
        	jQuery("#"+_divId).html("");
        	ImagePlugins.addSimpleItem({"place" : _divId,"mutiple" : isMutiple, "setMain" : setMain});
        },
        replaceImgs : function(_param) {
        	//ImagePlugins.clearPlugin(_param.place);
        	var pathArr = _param.imgPaths.split(",");
        	for (var i=0;i<pathArr.length;i++) {
        		ImagePlugins.addImgBySrc(_param.place, pathArr[i]);
        	}
        },
        setMainPic : function(_divId, _index) {
        	jQuery("#"+_divId).find(".work").eq(_index).addClass("redBor");
        	jQuery("#"+_divId).find("img[alt='Photo']").eq(_index).attr("_isMainPic", "Y");
        },
        resetImgs : function(_divId){
        	var imgObj = jQuery("#"+_divId).find("img[alt='Photo']").eq(0);
        	imgObj.attr("src", ctx + "/images/nopic.jpg");
        	imgObj.attr("onerror", "javascript:this.src='"+ctx+"/images/nopic.jpg'");
        	imgObj.removeAttr("dbpath");
        }
    };

}();